/**
 * Created by jiexin on 2017/9/15.
 */
layui.use(['form', 'element', 'layer', 'table'], function() {
    var form = layui.form;
    var element = layui.element;
    var table = layui.table;
    var $ = layui.jquery;
    var layer = layui.layer;

    var keyleftall = document.getElementById("key_left");
    var keyleftw = keyleftall.offsetWidth - 20;
    var keylefth = keyleftall.offsetHeight - 80;
    var leftki = keyleftw  * 0.08;
    var leftkn = keyleftw * 0.2;
    var leftkd = keyleftw * 0.27;
    var leftks = keyleftw * 0.15;
    var leftkdd = keyleftw * 0.3;

    var keyrightall = document.getElementById("key_right");
    var keyrightw = keyrightall.offsetWidth-60;
    var keyrighth = keyrightall.offsetHeight - 120;



    var table_format_keys = [[
         {field: 'key_id', align: 'center', title: 'ID', width: leftki}
         , {field: 'key_name', align: 'center', title: 'Yaml名称', width: leftkn}
         , {field: 'key_describe', title: '描述', width: leftkd}
         , {field: 'key_using', title: '状态', width: leftks, templet: '#keystatus'}
         , {fixed: 'right',width: leftkdd, align: 'center',  title: '操作', toolbar: '#keysDemo', templet: '#keysDemo'}
    ]];

    $('.layui-table').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        //var tableid = document.getElementById('update').id;
        console.log(tableid);
        console.log(keys_list);
        createtable(etaleid,tableid,keys_list,table_format_keys,keylefth,keyleftw);
        yamltool(toolid,tableid);
    });

    var keytable;
    function createtable(etaleid,tableid,datas,table_format,table_height, table_width) {
        keytable = table.render({
            elem: etaleid,
            id: tableid,
            //url: '/demo/table/user/',
            height: table_height,
            width:table_width,
            limit: 10,
            page: true,
            stateSave: true, //是否打开客户端状态记录功能,此功能在ajax刷新纪录的时候不会将个性化设定回复为初始化状态
            processing: true, //DataTables载入数据时，是否显示‘进度’提示
            scrollCollapse: true, //是否开启DataTables的高度自适应，当数据条数不够分页数据条数的时候，插件高度是否随数据条数而改变
            searching: true, //是否允许Datatables开启本地搜索
            data: datas,
            cols: table_format
        });
    }

    function yamltool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);

            //tr.index()
            if (layEvent === 'check') {
                layer.msg( keys_list[tr.index()]["key_public"],{
                    time: 20000,
                    //20s后自动关闭
                    btn: ['关闭'],
                    success: function (layero) {
                        var btn = layero.find('.layui-layer-btn');
                        var btntrue = layero.find('.layui-layer-btn0');
                        btn.css('text-align', 'center');
                    }
                })
            } else if (layEvent === 'del') {
                layer.msg('确定删除这个key！', {
                    time: 20000,
                    //20s后自动关闭
                    btn: ['确认', '取消'],
                    success: function (layero) {
                        var btn = layero.find('.layui-layer-btn');
                        var btntrue = layero.find('.layui-layer-btn0');
                        btn.css('text-align', 'center');
                        btntrue.on('click', function () {
                            $.ajax({
                                url: "/yaml-del/",
                                dataType: 'json',
                                type: 'POST',
                                data: {"id": data["key_id"], "type":"key"},
                                success: function (statusdata) {
                                    if (statusdata["status"] === 0){
                                        keytable.reload({
                                             data: statusdata["data_list"]
                                        });
                                    }else if (statusdata["status"] === 2){
                                        layer.msg("密钥已关联组，无法禁用！")
                                    }else{
                                        layer.msg("操作失败！")
                                    }

                                }
                            })
                        })
                    }
                });
            } else if (layEvent === 'disable') {

                dissend(tr,1)
            } else if (layEvent === 'enable') {

                dissend(tr,0)
            }
        });
    }

     function dissend(sendtr,sendstatus) {
        $.ajax({
            url: '/yaml-dis/',
            dataType: 'json',
            type: 'POST',
            data: {"id": keys_list[sendtr.index()]["key_id"], "status":sendstatus, "type": "key"},
            success: function (statusdata) {
                if (statusdata["status"] === 0) {
                    if (sendstatus === 0){
                        sendtr.find("td").find(".laytable-cell-1-key_using").html('<span class="label label-success">已启用</span>');
                        sendtr.find("td").find(".laytable-cell-1-4").find(".layui-btn-enable").replaceWith('<a id="disable" class="layui-btn layui-btn-xs layui-btn-disable" lay-event="disable">禁用</a>');
                        keys_list[sendtr.index()]["key_using"] = sendstatus;
                        layer.msg("启用成功！")
                    } else {
                        sendtr.find("td").find(".laytable-cell-1-key_using").html('<span class="label label-default">已禁用</span>');
                        sendtr.find("td").find(".laytable-cell-1-4").find(".layui-btn-disable").replaceWith('<a id="enable" class="layui-btn layui-btn-xs layui-btn-enable" lay-event="enable">启用</a>');
                        keys_list[sendtr.index()]["key_using"] = sendstatus;
                        layer.msg("禁用成功！")
                    }
                }else if (statusdata["status"] === 2){
                    layer.msg("密钥已关联组，无法禁用！")
                } else {
                    layer.msg("状态修改失败")
                }
            }
        })
    }


    form.on('submit(submitkey)', function(data){
        console.log(data.field); //当前容器的全部表单字段，名值对形式：{name: value}
        var keydata = data.field;
        $.ajax({
            url: '/yaml-add-key/',
            dataType: 'json',
            type: 'POST',
            data: {"data": JSON.stringify(keydata)},
            success: function (statusdata) {
                if (statusdata["status"] === 0) {
                    $('#resets').trigger("click");
                    keytable.reload({
                        data: statusdata["keys_list"]
                    });
                    keys_list = statusdata["keys_list"];
                    layer.msg('添加成功！')

                }else if (statusdata["status"] === 1) {
                    layer.msg('添加失败！')
                }else {
                    layer.msg(statusdata["status"])
                }
            }
        })
    });


    $('.demoTable .layui-btn').on('click', function() {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
});